<?php
namespace app\admin\model;
use app\common\model\ShopCategory as ShopCategoryModel;
use think\Cache;

/**
 * 门店分类模型
 */
class ShopCategory extends ShopCategoryModel
{
    /**
     * 添加新记录
     */
    public function add($data)
    {
        $this->deleteCache();
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑记录
     */
    public function edit($data)
    {
        $this->deleteCache();
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 删除分类
     */
    public function remove()
    {
        // 判断是否存在门店
        if ($shopCount = (new Shop)->where(['shop_category_id'=>$this->shop_category_id])->count()) {
			$this->error = '该分类下存在' . $shopCount . '个门店，不允许删除';
            return false;
        }
        // 判断是否存在子分类
        if ((new self)->where(['parent_id' => $this->shop_category_id])->count()) {
			$this->error = '该分类下存在子分类，请先删除';
            return false;
        }
        $this->deleteCache();
        return $this->delete();
    }

    /**
     * 删除缓存
     */
    private function deleteCache()
    {
        return Cache::rm('shop_category_hema');
    }

}
